package com.zy.mc_module.utils.retrofit;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.zy.mc_module.MainActivity;
import com.zy.mc_module.R;
import com.zy.mc_module.common.Constant;
import com.zy.mc_module.mvp.base.BasePresenter;
import com.zy.mc_module.mvp.bean.BaseBean;
import com.zy.mc_module.mvp.bean.TokenBean;
import com.zy.mc_module.utils.*;
import com.zy.mc_module.utils.retrofit.disposable.SubscriptionManager;
import com.zy.mc_module.utils.retrofit.error.BaseException;
import com.zy.mc_module.utils.retrofit.error.ThdException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created on 18/10/22
 */
public abstract class RxObserver<T> implements Observer<T> {
    private Dialog dialog;
    private Context context;
    private BasePresenter mPresenter;

    public RxObserver(BasePresenter presenter, Context context) {
        this.context = context;
        this.mPresenter = presenter;
    }

    public RxObserver(BasePresenter presenter, Context context, String title) {
        this.context = context;
        this.mPresenter = presenter;
        dialog = createLoadingDialog(context, title, false);
    }

    public RxObserver(BasePresenter presenter, Context context, boolean isShow) {
        this.context = context;
        this.mPresenter = presenter;
        if (isShow)
            dialog = createLoadingDialog(context, "请稍后...", false);
    }

    public RxObserver(BasePresenter presenter, Context context, String title, boolean iscancel) {
        this.context = context;
        this.mPresenter = presenter;
        dialog = createLoadingDialog(context, title, iscancel);
    }

    /***
     * 显示加载框
     */
    private void showDialog() {
        if (null != dialog && !dialog.isShowing()) {
            try {
                dialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * 关闭加载框
     */
    private void dismissDialog() {
        if (null != dialog && dialog.isShowing()) {
            try {
                dialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onSubscribe(Disposable d) {
        //添加订阅关系
        if (null != mPresenter) {
            mPresenter.addDisposable(d);
        }
        //SubscriptionManager.getInstance().add(d);
        //显示加载框
        showDialog();
    }

    @Override
    public void onNext(T t) {
        if (null != t) {
            if (t instanceof BaseBean) {
                //0成功/其他失败
                BaseBean baseBean = (BaseBean) t;
                Logs.Log_e("HttpResult", "onNext-->  " + baseBean.toString());
//                if (0 == baseBean.code || -11 == baseBean.code || -12 == baseBean.code) {
                if (0 == baseBean.code || 94 == baseBean.code || 95 == baseBean.code) {
                    //code==0,正确返回
                    onBaseNext(t);
                } else if (baseBean.code == -10) {
                    dismissDialog();
                    return;
                } else {
                    //其他code
                    ThdException e = new ThdException(baseBean.msg, baseBean.code);
                    onBaseError(e);
                }
            } else {
                onBaseNext(t);
            }
        } else {
            ThdException e = new ThdException("请求失败，请稍后再试");
            onBaseError(e);
        }
        //关闭加载框
        dismissDialog();
    }

    @Override
    public void onError(Throwable e) {
        Logs.Log_e("HttpResult", "error-->  " + e.toString());
        if (e instanceof HttpException && ((HttpException)e).code() == 401) {
            refreshToken();
        }
        //关闭加载框
        dismissDialog();
        //其他错误
        onBaseError(BaseException.handleException(e));
    }

    /**
     * token过期，重新获取token信息
     */
    private void refreshToken() {

//                {
//                    "error": "invalid_token",
//                        "error_description": "Access token expired: eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsib2F1dGgyLXJlc291cmNlIl0sInVzZXJfbmFtZSI6IjE1NTExMTExMTExIiwic2NvcGUiOlsicmVhZCJdLCJpZCI6MzEsImV4cCI6MTY2NTkyNjk1NCwianRpIjoiYzY1YTZmYjctYmY4ZC00ZGI3LWFlMzUtMTM4N2U2MTM0OGQyIiwiY2xpZW50X2lkIjoicmVzb3VyY2VTZXJ2ZXIifQ.K_5oB9VQx-Er7Ok5nTdqLv8jaexl-DdshHHxmbAHAi8sf2v2Qjghtyj5Fm4OUEeawKfZ6b7EgQxS0ez_XRkKMdZa_rEcvLYaHjM4i1oUJxQUKAUQiIhuzbFJ8OICVuII11VWE6UkOE4z0oQNEQw2heDfOizEAPkHIApKk9QnzN1l0nypprqNZ_XbTHBaYm_jwihmAmFB7lXzxIM_63B2J6lP0u0aUXbsX_wAlcgoNRLSfxOUo2Xth9jvkDzhv4U38E6ELdZFtF6uNZhbeAL8uR7YcIGGJRy_fO8mbjZj_N2zd6PaWYyCaYBaVQ8n9f8oTDQa2REYmgkqkr_kXcyJSQ"
//                }
        String tokenInfo = SPUtil.getString(Constant.USER_TOKEN_INFO, "");
        if (!StringsUtils.isEmpty(tokenInfo)) {
            TokenBean bean = GsonUtil.gsonToBean(tokenInfo, TokenBean.class);
            RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"),bean.getRefresh_token());
            RetrofitManager.getInstance().getApi().refreshToken(body).compose(RxTransform.schedule())
                    .subscribe(new RxObserver<TokenBean>(mPresenter, context) {
                        @Override
                        protected void onBaseNext(TokenBean tokenBean) {
                            SPUtil.putString(Constant.USER_TOKEN_INFO, GsonUtil.gsonString(tokenBean));
                        }

                        @Override
                        protected void onBaseError(ThdException e) {

                        }
                    });
        }
    }

    @Override
    public void onComplete() {
        //关闭加载框
        dismissDialog();
    }

    protected abstract void onBaseNext(T t);

    protected abstract void onBaseError(ThdException e);

    /***
     * Token 过期
     */
    private void stopToken() {
        //Token无效重新登录
        UserUtils.exitLogin();
        SubscriptionManager.getInstance().cancelall();
        Toast.makeText(context, "登录过期，请重新登录", Toast.LENGTH_SHORT).show();
        try {
            Intent intent = new Intent(context, MainActivity.class);
            context.startActivity(intent);
            Activity activity = (Activity) context;
            if (!activity.toString().contains("MainActivity") && !activity
                    .isFinishing()) {
                activity.finish();
            }
        } catch (Exception es) {
            Logs.Log_e("HttpResult", "token无效,跳转登录页失败-->  " + es.getMessage());
            es.printStackTrace();
        }
    }

    /**
     * 自定义的progressDialog
     *
     * @param title
     * @return
     */
    public Dialog createLoadingDialog(Context context, String title, boolean iscancel) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_loading, null);
        TextView tv_title = view.findViewById(R.id.loading_title);
        tv_title.setText(title);
        Dialog dialog = new Dialog(context, R.style.LoadingDialog);
        dialog.setCanceledOnTouchOutside(iscancel);
        dialog.setCancelable(iscancel);
        dialog.setContentView(view);
        return dialog;
    }
}
